<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="60%">
    <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="120">
      <el-row>
        <el-col :span="8">
          <el-form-item label="所属企业" prop="colliery">
            <el-select clearable filterable style="width: 100%" v-model="formData.colliery" :disabled="!!rowId"
              placeholder="请选择所属企业">
              <el-option v-for="item in companyList" :key="item.id" :label="item.tenantName" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="煤种名称" prop="coalName">
            <el-input :maxlength="20" v-model="formData.coalName" :disabled="!!rowId" placeholder="请输入煤种名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="产品类型" prop="productType">
            <el-select clearable filterable style="width: 100%" v-model="formData.productType" :disabled="!!rowId"
              placeholder="请选择产品类型">
              <el-option v-for="item in getStrDictOptions(DICT_TYPE.PRODUCT_TYPE)" :key="item.value" :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="热值" prop="calorificValue">
            <el-input :maxlength="20" v-model="formData.calorificValue" placeholder="请输入热值" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="硫" prop="sulfur">
            <el-input :maxlength="20" v-model="formData.sulfur" placeholder="请输入硫" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="灰" prop="ash">
            <el-input :maxlength="20" v-model="formData.ash" placeholder="请输入灰" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="全水" prop="allWater">
            <el-input :maxlength="20" v-model="formData.allWater" placeholder="请输入全水" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="内水" prop="mad">
            <el-input :maxlength="20" v-model="formData.mad" placeholder="请输入内水" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="灰熔点" prop="ashFusionPoint">
            <el-input :maxlength="20" v-model="formData.ashFusionPoint" placeholder="请输入灰熔点" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="可磨指数" prop="grindabilityIndex">
            <el-input :maxlength="20" v-model="formData.grindabilityIndex" placeholder="请输入可磨指数" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="焦渣特征" prop="panBreeze">
            <el-input :maxlength="20" v-model="formData.panBreeze" placeholder="请输入焦渣特征" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="挥发分" prop="volatileMatter">
            <el-input :maxlength="20" v-model="formData.volatileMatter" placeholder="请输入挥发分" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>

        <el-col :span="8">
          <el-form-item label="标准热值" prop="defaultCalorificValue">
            <el-input :maxlength="10" type="number" v-model="formData.defaultCalorificValue" placeholder="请输入标准热值" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否展示" prop="showStatus">
            <el-select clearable style="width: 100%" v-model="formData.showStatus" placeholder="请选择是否展示">
              <el-option v-for="item in getIntDictOptions(DICT_TYPE.YES_NO_TYPE)" :key="item.value" :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否参与分析" prop="analyseStatus">
            <el-select clearable style="width: 100%" v-model="formData.analyseStatus" placeholder="请选择是否参与分析">
              <el-option v-for="item in getIntDictOptions(DICT_TYPE.YES_NO_TYPE)" :key="item.value" :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="三方ID" prop="coalId">
            <el-input :maxlength="20" v-model="formData.coalId" :disabled="true" placeholder="请输入三方ID" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="数据来源" prop="platformSource">
            <el-select clearable style="width: 100%" v-model="formData.platformSource" :disabled="true"
              placeholder="请选择数据来源">
              <el-option v-for="item in getIntDictOptions(DICT_TYPE.PLATFORM_SOURCE)" :key="item.value"
                :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="化验报告" prop="assayReport">
            <UploadImg v-model="formData.assayReport" :limit="1" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
  import { cloneDeep } from 'lodash'
  import * as coalMarket from '@/api/coalMarket'
  import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'

  const rowId = ref();
  const formRef = ref()
  const message = useMessage()
  const dialogVisible = ref(false)
  const emit = defineEmits(['success'])
  const dialogTitle = ref()
  const companyList = ref([])
  const formLoading = ref(false)
  const formData = ref({
    coalName: undefined,
    colliery: undefined,
    productType: undefined,
    calorificValue: undefined,
    sulfur: undefined,
    ash: undefined,
    allWater: undefined,
    mad: undefined,
    ashFusionPoint: undefined,
    grindabilityIndex: undefined,
    panBreeze: undefined,
    volatileMatter: undefined,
    assayReport: undefined,
    defaultCalorificValue: undefined,
    showStatus: undefined,
    analyseStatus: undefined,
    coalId: undefined,
    platformSource: 3
  })

  const formRules = reactive({
    colliery: [{ required: true, message: '请选择所属企业', trigger: 'change' }],
    coalName: [{ required: true, message: '请输入煤种名称', trigger: 'blur' }],
    productType: [{ required: true, message: '请选择产品类型', trigger: 'change' }],
    calorificValue: [{ required: true, message: '请输入热值', trigger: 'blur' }],
    sulfur: [{ required: true, message: '请输入硫', trigger: 'blur' }]
  })

  const open = async (id) => {
    resetForm()
    dialogVisible.value = true
    rowId.value = id
    if (id) {
      dialogTitle.value = '编辑'
    } else {
      dialogTitle.value = '新增'
    }
    await getCompanyList()
    if (id) {
      getCollieryMgrById()
    }
  }

  const resetForm = () => {
    Object.keys(formData.value).forEach(key => {
      if (key === 'platformSource') {
        formData.value[key] = 3
      } else {
        formData.value[key] = undefined
      }
    })
  }

  const getCompanyList = async () => {
    const res = await coalMarket.getCompanyList()
    companyList.value = res || []
  }

  const getCollieryMgrById = async () => {
    const res = await coalMarket.getCollieryMgrById({ id: rowId.value })
    Object.keys(formData.value).forEach(key => {
      if (key === 'colliery') {
        formData.value[key] = companyList.value.find(e => {
          if (e.tenantId) {
            return e.tenantId.toString() === res.collieryId && e.tenantName === res.collieryName
          } else {
            return e.tenantName === res.collieryName
          }
        })?.id
      } else {
        formData.value[key] = res[key]
      }
    })
  }

  const submitForm = async () => {
    if (!formRef) return
    const valid = await formRef.value.validate()
    if (!valid) return
    formLoading.value = true
    if (rowId.value) {
      updateCollieryInfo()
    } else {
      createCollieryInfo()
    }
  }

  const createCollieryInfo = async () => {
    try {
      const data = cloneDeep(formData.value)
      data['companyId'] = companyList.value.find(e => e.id === data.colliery)?.id
      data['collieryId'] = companyList.value.find(e => e.id === data.colliery)?.tenantId
      data['collieryName'] = companyList.value.find(e => e.id === data.colliery)?.tenantName
      delete data.colliery
      const res = await coalMarket.createCollieryInfo(data)
      if (res) {
        message.success('新增成功')
        emit('success')
        dialogVisible.value = false;
      }
    } finally {
      formLoading.value = false
    }
  }

  const updateCollieryInfo = async () => {
    try {
      const data = cloneDeep(formData.value)
      data['id'] = rowId.value
      data['companyId'] = companyList.value.find(e => e.id === data.colliery)?.id
      data['collieryId'] = companyList.value.find(e => e.id === data.colliery)?.tenantId
      data['collieryName'] = companyList.value.find(e => e.id === data.colliery)?.tenantName
      delete data.colliery
      const res = await coalMarket.updateCollieryInfo(data)
      if (res) {
        message.success('编辑成功')
        emit('success')
        dialogVisible.value = false;
      }
    } finally {
      formLoading.value = false
    }
  }

  defineExpose({ open })
</script>